import urllib2

script = urllib2.urlopen("https://creator-dev.googlecode.com/svn/trunk/scripts/bounding_box_tree.py")
exec(script.read())
script.close()

def make_polygon_rec(pt_list):
	poly = mgNewRec(fltPolygon)
	for pt in pt_list:
		vertex = mgNewRec(fltVertex)
		mgSetVtxCoord(vertex, pt.x, pt.y, pt.z)
		mgAppend(poly, vertex)
	return poly

def make_box_object_rec(box):
	poly_list = [
		make_polygon_rec([
			mgMakeCoord3d(box.min.x, box.max.y, box.min.z),
			mgMakeCoord3d(box.min.x, box.max.y, box.max.z),
			box.max,
			mgMakeCoord3d(box.max.x, box.max.y, box.min.z)]),
		make_polygon_rec([
			box.min,
			mgMakeCoord3d(box.max.x, box.min.y, box.min.z),
			mgMakeCoord3d(box.max.x, box.min.y, box.max.z),
			mgMakeCoord3d(box.min.x, box.min.y, box.max.z)]),
		make_polygon_rec([
			box.min,
			mgMakeCoord3d(box.min.x, box.min.y, box.max.z),
			mgMakeCoord3d(box.min.x, box.max.y, box.max.z),
			mgMakeCoord3d(box.min.x, box.max.y, box.min.z)]),
		make_polygon_rec([
			mgMakeCoord3d(box.max.x, box.min.y, box.min.z),
			mgMakeCoord3d(box.max.x, box.max.y, box.min.z),
			box.max,
			mgMakeCoord3d(box.max.x, box.min.y, box.max.z)]),
		make_polygon_rec([
			box.min,
			mgMakeCoord3d(box.min.x, box.max.y, box.min.z),
			mgMakeCoord3d(box.max.x, box.max.y, box.min.z),
			mgMakeCoord3d(box.max.x, box.min.y, box.min.z)]),
		make_polygon_rec([
			mgMakeCoord3d(box.min.x, box.min.y, box.max.z),
			mgMakeCoord3d(box.max.x, box.min.y, box.max.z),
			box.max,
			mgMakeCoord3d(box.min.x, box.max.y, box.max.z)])]
	box_rec = mgNewRec(fltObject)
	for poly in poly_list:
		mgSetAttList(poly, fltPolyTransparency, 0x8888)
		mgAppend(box_rec, poly)
	return box_rec

def draw_box_tree(box_tree):
	db = mgGetCurrentDb()
	box_tree_group = mgNewRec(fltGroup)
	mgSetName(box_tree_group, "Box Tree")
	mgAppend(db, box_tree_group)
	groups = {}
	for box in box_tree:
		depth = box_tree.iterator_depth
		if not groups.get(depth):
			group = mgNewRec(fltGroup)
			mgSetName(group, "D" + str(depth))
			mgAppend(box_tree_group, group)
			groups[depth] = group
		mgAppend(groups[depth], make_box_object_rec(box))